import json

from django.http import HttpResponse, JsonResponse

from django.shortcuts import render
import os
import django

os.environ.setdefault("DJANGO_SETTINGS_MODULE", "green.settings")
django.setup()

# render请求
from green import models
from green import predict


def two(request):
    return render(request, "two/two.html")


def twoPredict(request):
    return render(request, "two/twoPredict.html")


def initTwoPredict(request):
    predict.initTwoPredict()
    return HttpResponse("构造成功！")


def initTwo():
    bigJson = {}
    yearList = ['y' + str(i) for i in range(1997, 2018)]
    print(yearList)
    for oneyear in yearList:
        queryCity = models.Provenceco2List.objects.values('city', oneyear)
        tempList = []
        for city in queryCity:
            tempList.append({'city': city['city'], 'MtCO2': city[oneyear]})
        bigJson[oneyear[1:]] = tempList
    s = json.dumps(bigJson)
    f = open('../../templates/two/showTwo.json', 'w', encoding='UTF-8')
    f.write(s)
    f.close()
    print("构造showTwo.json成功！")
    return HttpResponse("构造成功！")


def showTwo(request):
    year = request.GET.get('year')
    date = str(year)

    f = open('templates/two/showTwo.json', 'r', encoding='utf-8')
    bigJson = f.read()
    f.close()
    bigDict = json.loads(bigJson)
    data = bigDict[date]

    cars = {"data": data}
    response = HttpResponse(json.dumps(cars), content_type='application/json; charset=utf-8')
    return response


def showTwoPredict(request):
    f = open('templates/two/predict_new.json.json', 'r', encoding='utf-8')
    person = f.read()
    f.close()

    # person_str = json.dumps(person)
    # response = HttpResponse(person_str , content_type='application/json; charset=utf-8')
    response = HttpResponse(person, content_type='application/json; charset=utf-8')
    return response


if __name__ == '__main__':
    initTwo()
